package com.oa.leave.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.activiti.engine.task.Task;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oa.entity.ExtPageable;
import com.oa.entity.ExtjsAjaxResult;
import com.oa.entity.WorkflowVariable;
import com.oa.leave.dto.LeaveDTO;
import com.oa.leave.dto.TaskDTO;
import com.oa.leave.entity.Leave;
import com.oa.leave.service.ILeaveService;
import com.oa.log.annotation.Log;
import com.oa.util.SessionUtil;

@Controller
@RequestMapping(value = "/leave")
public class LeaveController {
	@Resource
	private ILeaveService leaveService;

	@RequestMapping(value = "/saveOrUpdate")
	@Log(oprate = "提交或更新请假申请")
	public @ResponseBody ExtjsAjaxResult saveOrUpdate(Leave leave) {
		if (leave.getProcessInstanceId() == null) {
			leave.setProcessInstanceId("");
		}
		try {
			leaveService.save(leave);
			return new ExtjsAjaxResult(true, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtjsAjaxResult(false, "操作失败!");
		}
	}

	@RequestMapping(value = "/delete")
	@Log(oprate = "删除请假申请")
	public @ResponseBody ExtjsAjaxResult delete(Long id) {
		try {
			leaveService.delete(id);
			return new ExtjsAjaxResult(true, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtjsAjaxResult(false, "操作失败!");
		}
	}

	@RequestMapping(value = "/leave-list")
	public @ResponseBody Page<Leave> findLeaveByUserId(HttpSession session, ExtPageable pageable) {
		Page<Leave> page = new PageImpl<Leave>(new ArrayList<Leave>(), pageable.getPageable(), 0);
		try {
			String userId = SessionUtil.getName(session);
			page = leaveService.findLeave(userId, pageable.getPageable());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
	}

	@GetMapping("/leave-history-list")
	public @ResponseBody Page<Leave> findLeaveHistoryList(Leave leave, ExtPageable pageable) {
		Page<Leave> page = leaveService.findLeaveHistory(leaveService.getWhereClause(leave), pageable.getPageable());

		for (Leave l : page) {
			System.out.println(l);
		}

		return page;
	}
	/*-------------------------------------流程引擎web层------------------------------------------*/

	/**
	 * 启动流程
	 * 
	 * @param leaveId
	 *            请假信息Id
	 * @param session
	 *            通过会话获取登录用户(请假人)
	 * @return
	 */
	@RequestMapping(value = "/start")
	public @ResponseBody ExtjsAjaxResult start(@RequestParam(name = "id") Long leaveId, HttpSession session) {
		try {
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("deptLeader", leaveService.getDeptManager(SessionUtil.getUserInfo(session).getDept()));// andy
			variables.put("applyUserId", SessionUtil.getName(session));

			leaveService.startWorkflow(leaveId, variables);

			return new ExtjsAjaxResult(true, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtjsAjaxResult(false, "操作失败!");
		}
	}

	/**
	 * 查询待处理流程任务
	 * 
	 * @param pageable
	 *            分页对象
	 * @param session
	 *            通过会话获取登录用户(请假人)
	 * @return
	 */
	@RequestMapping(value = "/findTasks")
	public @ResponseBody Page<LeaveDTO> findTodoTasks(HttpSession session, ExtPageable pageable) {
		Page<LeaveDTO> page = new PageImpl<LeaveDTO>(new ArrayList<LeaveDTO>(), pageable.getPageable(), 0);
		try {
			page = leaveService.findTodoTasks(SessionUtil.getName(session), pageable.getPageable());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return page;
	}

	/**
	 * 签收任务
	 */
	@RequestMapping(value = "claim/{id}")
	@Log(oprate = "签收请假申请")
	public @ResponseBody ExtjsAjaxResult claim(@PathVariable("id") String taskId, HttpSession session) {
		try {
			leaveService.claim(taskId, SessionUtil.getName(session));
			return new ExtjsAjaxResult(true, "任务签收成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtjsAjaxResult(false, "任务签收失败!");
		}
	}

	/**
	 * 完成任务
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "complete")
	@Log(oprate = "审批请假申请")
	public @ResponseBody ExtjsAjaxResult complete(LeaveDTO leaveDTO, WorkflowVariable var) {
		try {
			Map<String, Object> variables = var.getVariableMap();
			leaveService.complete(leaveDTO.getTaskId(), variables);

			Leave leave = leaveService.findOne(leaveDTO.getId());

			leave.setBackReason(leaveDTO.getBackReason());
			leave.setRealityStartTime(leaveDTO.getRealityStartTime());
			leave.setRealityEndTime(leaveDTO.getRealityEndTime());
			leave.setState("审批中");

			if ("hrAudit".equals(leaveDTO.getTaskDefinitionKey())) {
				leave.setState("已通过审批");
			}
			if ("reportBack".equals(leaveDTO.getTaskDefinitionKey())) {
				leave.setState("已完成");
			}
			if (leaveDTO.getBackReason() != null && leaveDTO.getBackReason().trim().length() > 0) {
				leave.setState("申请被驳回");
			}
			if ("modifyApply".equals(leaveDTO.getTaskDefinitionKey())
					&& !(leaveService.isProcessInstanceActive(leave.getProcessInstanceId()))) {
				leave.setState("申请已取消");
			}

			leaveService.save(leave);

			return new ExtjsAjaxResult(true, "任务完成成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtjsAjaxResult(false, "任务完成失败!");
		}
	}

	@RequestMapping("/isChangeable")
	public @ResponseBody ExtjsAjaxResult isChangeable(String processInstanceId) {
		if (leaveService.isProcessInstanceActive(processInstanceId)) {
			return new ExtjsAjaxResult(false, "该申请正在进行中");
		}
		if (leaveService.isProcessInstanceExist(processInstanceId)) {
			return new ExtjsAjaxResult(false, "该表单已提交过");
		}
		return new ExtjsAjaxResult(true, "该申请正没有在进行");
	}

	// @GetMapping("/getManager")
	// private @ResponseBody String getManager(HttpSession session) {
	// String leader =
	// leaveService.getDeptManager(SessionUtil.getUserInfo(session).getDept());
	// return leader;
	// }

	@GetMapping("/getTask")
	public @ResponseBody TaskDTO getTaskDefKey(String processInstanceId) {
		TaskDTO taskDTO = new TaskDTO();
		Task task = leaveService.getTask(processInstanceId);
		taskDTO.setTaskDefinitionKey(task.getTaskDefinitionKey());
		taskDTO.setTaskId(task.getId());

		return taskDTO;

	}

	@GetMapping("/findLateLeave")
	public @ResponseBody Page<Leave> findLateLeave() {
		Page<Leave> page = leaveService.findLateLeave();
		return page;
	}
}
